/**
 * 101. 对称二叉树
 *
 * 【简单】
 *
 * 给你一个二叉树的根节点 root ， 检查它是否轴对称。
 *
 * 示例 1：
 * 【https://pic.leetcode.cn/1698026966-JDYPDU-image.png】
 * 输入：root = [1,2,2,3,4,4,3]
 * 输出：true
 *
 * 示例 2：
 * 【https://pic.leetcode.cn/1698027008-nPFLbM-image.png】
 * 输入：root = [1,2,2,null,3,null,3]
 * 输出：false
 */

import { TreeNode } from '../utils/tree'

// 递归
var isSymmetric = function isSymmetric(root: TreeNode | null): boolean {
	if (root == null) {
		return true
	}

	return isEqual(root.left, root.right)

	function isEqual(left, right) {
		if (left == null && right == null) {
			return true
		}
		if (left == null || right == null) {
			return false
		}

		return (
			left.val === right.val &&
			isEqual(left.left, right.right) &&
			isEqual(left.right, right.left)
		)
	}
}

// 迭代
var isSymmetric = function isSymmetric(root: TreeNode | null): boolean {
	let p = root
	let q = root

	if (p == null && q == null) {
		return true
	}

	const queue = [p, q]
	while (queue.length) {
		p = queue.shift() as TreeNode | null
		q = queue.shift() as TreeNode | null

		if (p == null && q == null) {
			continue
		}

		if (p == null || q == null) {
			return false
		}

		if (p.val !== q.val) {
			return false
		}

		queue.push(p.left, q.right)
		queue.push(p.right, q.left)
	}

	return true
}
